﻿using Microsoft.Extensions.Configuration;

namespace Utils
{
    public class AppSettings
    {
        private static IConfiguration Configuration { get; set; }

        public AppSettings(IConfiguration configuration)
        {
            Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
        }

        public static string App(params string[] sections)
        {
            return sections == null || sections.Length == 0 ? string.Empty : GetConfigurationValue(sections);
        }

        private static string GetConfigurationValue(string[] sections)
        {
            string key = string.Join(":", sections);

            try
            {
                return Configuration[key] ?? string.Empty; // 防止找不到键时返回 null
            }
            catch (KeyNotFoundException)
            {
                LogError($"配置项 '{key}' 未找到.");
            }
            catch (Exception ex)
            {
                LogError($"发生错误: {ex.Message}");
            }
            return string.Empty;
        }

        private static void LogError(string message)
        {
            // 这里可以替换为具体的日志框架
            Console.WriteLine(message);
        }

        public static List<T> App<T>(params string[] sections)
        {
            List<T> list = new();
            if (Configuration != null && sections.Any())
            {
                try
                {
                    Configuration.Bind(string.Join(":", sections), list);
                }
                catch (Exception ex)
                {
                    LogError($"发生错误: {ex.Message}");
                }
            }
            return list;
        }

        public static T Bind<T>(string key, T t)
        {
            Configuration.Bind(key, t);
            return t;
        }

        public static T GetAppConfig<T>(string key, T defaultValue = default)
        {
            string value = Configuration[key];
            return !string.IsNullOrEmpty(value) ? (T)Convert.ChangeType(value, typeof(T)) : defaultValue;
        }

        public static string GetConfig(string key)
        {
            return Configuration[key];
        }

        public static T Get<T>(string key)
        {
            return Configuration.GetSection(key).Get<T>();
        }
    }
}